/*
 * Copyright (c) 2020-2020, org.smartboot. All rights reserved.
 * project name: smart-license
 * file name: HttpServer.java
 * Date: 2020-07-22
 * Author: sandao (zhengjunweimail@163.com)
 */

package org.smartboot.license.server;

import org.smartboot.http.server.HttpBootstrap;
import org.smartboot.http.server.HttpRequest;
import org.smartboot.http.server.HttpResponse;
import org.smartboot.http.server.HttpServerHandle;
import org.smartboot.http.server.handle.HttpRouteHandle;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 三刀
 * @version V1.0 , 2020/7/2
 */
public class HttpServer {
    public static void main(String[] args) {


        HttpRouteHandle httpRouteHandle = new HttpRouteHandle();
        httpRouteHandle.route("/createLicense", new HttpServerHandle() {
            final File licenseDir = new File("./");

            @Override
            public void doHandle(HttpRequest request, HttpResponse response) throws IOException {
                try {
                    String owner = request.getParameter("owner");
                    String startTime = request.getParameter("startTime");
                    String endTime = request.getParameter("endTime");
                    String content = request.getParameter("content");
                    File fileDir = new File(licenseDir, owner);
                    if (!fileDir.isDirectory()) {
                        fileDir.mkdirs();
                    }
                    String date = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date());
                    File sourceFile = new File(fileDir, content + date + "_source.txt");
                    File licenseFile = new File(fileDir, content + date + "_license.txt");
                    LicenseServer server = new LicenseServer(sourceFile, licenseFile);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    server.createLicense(content.getBytes(), sdf.parse(startTime), sdf.parse(endTime));
//                server.createLicense(content.getBytes(),);
                    response.write(sourceFile.getAbsolutePath().getBytes());
                } catch (Exception e) {
                    throw new IOException(e);
                }
            }
        });
        HttpBootstrap httpBootstrap = new HttpBootstrap();

        httpBootstrap.pipeline().next(httpRouteHandle);
        httpBootstrap.start();

    }


}
